<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\MerchantApplication;
use think\facade\Log;
use think\Request;

class ApplicationController extends BaseController
{
    /**
     * 获取应用列表
     */
    public function list(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            $list = MerchantApplication::where('merchant_id', $merchant_id)
                ->order('id', 'desc')
                ->select();
                
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取应用列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 保存应用配置
     */
    public function save(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MerchantApplication');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            // 检查应用是否已存在
            $app = MerchantApplication::where([
                'merchant_id' => $merchant_id,
                'application_type' => $params['application_type']
            ])->find();
            
            if ($app) {
                // 更新
                $app->save([
                    'application_name' => $params['application_name'],
                    'app_id' => $params['app_id'],
                    'app_secret' => $params['app_secret'],
                    'token' => $params['token'] ?? '',
                    'encoding_aes_key' => $params['encoding_aes_key'] ?? '',
                    'additional_info' => $params['additional_info'] ?? '',
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            } else {
                // 新增
                MerchantApplication::create([
                    'merchant_id' => $merchant_id,
                    'application_name' => $params['application_name'],
                    'application_type' => $params['application_type'],
                    'app_id' => $params['app_id'],
                    'app_secret' => $params['app_secret'],
                    'token' => $params['token'] ?? '',
                    'encoding_aes_key' => $params['encoding_aes_key'] ?? '',
                    'additional_info' => $params['additional_info'] ?? ''
                ]);
            }
            
            return json(['code' => 0, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            Log::error('保存应用配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 